package com.sunflower.bath.common.interf.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import org.framework.mybatis.Criteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.sunflower.framework.utils.StringUtils;
import org.sunflower.framework.utils.UUIDUtils;

import com.sunflower.bath.common.contants.BathContants;
import com.sunflower.bath.common.interf.IJob;
import com.sunflower.bath.common.modle.ResultMsg;
import com.sunflower.bath.model.JobExecution;
import com.sunflower.bath.model.JobNeedExecut;
import com.sunflower.bath.model.JobParams;
import com.sunflower.bath.model.JobServerDb;
import com.sunflower.bath.model.JobTimer;

public class MysqlJob implements IJob{
	public static void main(String[] args) {
		String sql = "insert t_job_server_db (server_id,job_execution_id,address_ip,server_port,server_name,user_name,password,server_type) VALUES ('ytu80_0000000002','00002','www.ytu80.com','3306','bath','root','admin123','0');";
		JobNeedExecut job =new JobNeedExecut();
		job.setJobType(BathContants.JOB_TYPE_0);
		job.setAddressIp("www.ytu80.com");
		job.setServerPort("3306");
		job.setServerName("bath");
		job.setUserName("root");
		job.setPassword("admin123");
		job.setJobSql(sql);
		new MysqlJob().executJob(job);
		
	}
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	public ResultMsg executJob(JobNeedExecut job) {
		ResultMsg resultMsg = new ResultMsg();
		resultMsg.setIsSuccess(false);
		if(job==null||BathContants.JOB_TYPE_0!=job.getJobType()){
			logger.error("任务类型不匹配");
			resultMsg.setIsSuccess(false);
			resultMsg.setErrorCode("");
			resultMsg.setErrorMsg("任务类型不匹配");
			return resultMsg;
		}
		if(StringUtils.isNullOrBlank(job.getAddressIp()) 
				||StringUtils.isNullOrBlank(job.getServerPort())
				||StringUtils.isNullOrBlank(job.getServerName())
				||StringUtils.isNullOrBlank(job.getUserName())
				||StringUtils.isNullOrBlank(job.getPassword())){
			logger.error("数据库链接参数有误");
			resultMsg.setIsSuccess(false);
			resultMsg.setErrorCode("");
			resultMsg.setErrorMsg("数据库链接参数有误");
			return resultMsg;
		}
		Connection conn = null;
        String sql = job.getJobSql();
        String url = "jdbc:mysql://%s:%s/%s?user=%s&password=%s&&useUnicode=true&characterEncoding=UTF8";
        url = String.format(url,job.getAddressIp(),job.getServerPort(),job.getServerName(),job.getUserName(),job.getPassword());
        try {
            Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动
            logger.info("成功加载MySQL驱动程序");
            conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement(); // Statement里面带有很多方法，比如executeUpdate可以实现插入，更新和删除等
            int result = 1;
            logger.info("即将执行sql:{}",sql);
            result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数，如果返回-1就没有成功
            logger.info("sql执行完成，有{}行数据受到影响",result);
            resultMsg.setIsSuccess(true);
        } catch (SQLException e) {
        	logger.error("MySQL操作错误");
        	resultMsg.setIsSuccess(false);
			resultMsg.setErrorCode("");
			resultMsg.setErrorMsg(String.format("MySQL操作错误:\r\n %s",e));
            e.printStackTrace();
        } catch (Exception e) {
        	resultMsg.setIsSuccess(false);
			resultMsg.setErrorCode("");
			resultMsg.setErrorMsg(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
            	if(conn!=null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
        }
		return resultMsg;
	}
	
	
	
	@Override
	public ResultMsg addJob(JobNeedExecut job) {
		JobExecution jobExecution = new JobExecution();
		JobTimer jobTimer = new JobTimer();
		JobServerDb jobServerDb = new JobServerDb();
		JobParams jobParams = new JobParams();
		// 手动起事务
		DefaultTransactionDefinition defTrans = new DefaultTransactionDefinition();
		TransactionStatus ts = tranManager.getTransaction(defTrans);
		boolean result = false;
		
		try {
			String jobExecutionId = UUIDUtils.shortUuidAddTime();
			jobExecution.setJobExecutionId(jobExecutionId);
			jobExecution.setCreaterId(job.getCreaterId());
			jobExecution.setCreateTime(new Date());
			jobExecution.setJobDec(job.getJobDec());
			jobExecution.setJobIdentity(job.getJobIdentity());
			jobExecution.setJobMagType(job.getJobMagType());
			jobExecution.setJobName(job.getJobName());
			jobExecution.setJobSql(job.getJobSql());
			jobExecution.setJobThreadId(job.getJobThreadId());
			jobExecution.setJobType(job.getJobType());
			jobExecution.setUpdaterId(job.getCreaterId());
			jobExecution.setUpdateTime(new Date());
			
			String jobTimerId = UUIDUtils.shortUuidAddTime();
			jobTimer.setJobTimerId(jobTimerId);
			jobTimer.setCreaterId(job.getCreaterId());
			jobTimer.setCreateTime(new Date());
			jobTimer.setJobExecutionId(jobExecutionId);
			jobTimer.setJobMillisecondTimer(job.getJobMillisecondTimer());
			jobTimer.setJobRegularTimer(job.getJobRegularTimer());
			jobTimer.setTimerIdentity(job.getTimerIdentity());
			jobTimer.setTimerType(job.getTimerType());
			jobTimer.setUpdaterId(job.getCreaterId());
			jobTimer.setUpdateTime(new Date());
			
		} catch (Exception e) {
			e.printStackTrace();
			tranManager.rollback(ts);
		}finally {
			if (result) {
				tranManager.commit(ts);
			} else {
				tranManager.rollback(ts);
			}
		}
		return null; 
	}
	@Override
	public ResultMsg updateJob(JobNeedExecut job) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public ResultMsg deleteJob(JobNeedExecut job) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public ResultMsg selectJob(Criteria<JobNeedExecut> params) {
		// TODO Auto-generated method stub
		return null;
	}

	PlatformTransactionManager tranManager;
	public void setTranManager(PlatformTransactionManager tranManager) {
		this.tranManager = tranManager;
	}
	
}
